package com.bw.controller.Invoice;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.entity.Invoice.PiInvoice;
import com.bw.entity.Invoice.PiInvoiceLog;
import com.bw.entity.information.PiCustomer;
import com.bw.entity.information.PiMaterial;
import com.bw.entity.order.PiOrder;
import com.bw.entity.user.TbUser;
import com.bw.resp.ResponseResult;
import com.bw.service.Invoice.IPiInvoiceLogService;
import com.bw.service.Invoice.IPiInvoiceService;
import com.bw.service.information.IPiCustomerService;
import com.bw.service.order.IPiOrderService;
import com.bw.service.user.ITbUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lizhengqian
 * @since 2020-06-27
 */
@RestController
@RequestMapping("/Invoice/pi-invoice")
public class PiInvoiceController {
    public final Logger logger = LoggerFactory.getLogger(PiInvoiceController.class);
    @Autowired
    private IPiInvoiceService iPiInvoiceService;
    @Autowired
    private IPiCustomerService iPiCustomerService;
    @Autowired
    private IPiInvoiceLogService iPiInvoiceLogService;
    @Autowired
    private ITbUserService iTbUserService;
    @Autowired
    private IPiOrderService iPiOrderService;

    @PostMapping("/addInvoice")
    public ResponseResult addInvoice(@RequestBody PiInvoice piInvoice) {//回显 参数1：定义一个接前端传值的对象
        logger.info("添加申请发票");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            piInvoice.setIsDelete(1);
            piInvoice.setCreateDate(new Date());
            piInvoice.setCreateUser(piInvoice.getCustomerId());
            piInvoice.setState(0);
            iPiInvoiceService.saveOrUpdate(piInvoice);

            //添加发票记录
            PiInvoiceLog piInvoiceLog = new PiInvoiceLog();
            piInvoiceLog.setInvoiceId(piInvoice.getId());
            piInvoiceLog.setUserId(piInvoice.getId());
            piInvoiceLog.setUserName(piInvoice.getCustomername());
            piInvoiceLog.setRemarks("申请发票");
            piInvoiceLog.setUpdatetime(new Date());
            iPiInvoiceLogService.save(piInvoiceLog);

            result.setMessage("申请发票成功，请您等待审核");
        } catch (Exception e) {
            logger.error("添加申请发票失败");
            result.setMessage("添加申请发票失败" + e.toString());
            result.setSuccess(false);
        }
        return result;
    }

    /*
     *  查看当前客户下的发票列表
     *  1.客户id
     *  发票列表
     * */
    @PostMapping("/findpayList/{id}")
    public ResponseResult findpayList(@PathVariable long id,@RequestBody PiInvoice piInvoice) {
        logger.info("查询当前客户名下的发票开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("customerId", id);
            wrapper.eq("isDelete", 1);
            if(piInvoice.getAmount()!=null && !"".equals(piInvoice.getAmount())){
                wrapper.eq("amount",piInvoice.getAmount());
            }
            if(piInvoice.getLogisticsCym()!=null && !"".equals(piInvoice.getLogisticsCym().trim())){
                wrapper.eq("logisticsCym",piInvoice.getLogisticsCym());
            }
            if(piInvoice.getLogisticsCode()!=null && !"".equals(piInvoice.getLogisticsCode().trim())){
                wrapper.eq("logisticsCode",piInvoice.getLogisticsCode());
            }
            wrapper.orderByDesc("createDate");
            List list = iPiInvoiceService.list(wrapper);
            result.setResult(list);
            result.setMessage("查询发票成功");
            logger.info("查询当前客户名下的发票成功");
        } catch (Exception e) {
            logger.error("查询当前客户名下的发票失败");
            result.setMessage("查询当前客户名下的发票失败" + e.toString());
            result.setSuccess(false);
        }
        logger.info("查询当前客户名下的发票结束");
        return result;
    }
    @GetMapping("/findYc/{id}")
    public ResponseResult findYc(@PathVariable long id) {
        logger.info("查询当前客户名下隐藏的发票开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("customerId", id);
            wrapper.ne("isDelete", 0);
            List<PiInvoice> list = iPiInvoiceService.list(wrapper);
            result.setResult(list);
            //重新赋值状态
            for (PiInvoice piInvoice:list) {
                if(piInvoice.getIsDelete()==3){
                    piInvoice.setIsDelete(1);
                    iPiInvoiceService.saveOrUpdate(piInvoice);
                }
            }
            result.setMessage("操作成功");
            logger.info("查询当前客户名下隐藏的发票成功");
        } catch (Exception e) {
            logger.error("查询当前客户名下隐藏的发票失败");
            result.setMessage("查询当前客户名下隐藏的发票失败" + e.toString());
            result.setSuccess(false);
        }
        logger.info("查询当前客户名下隐藏的发票结束");
        return result;
    }

    /**
     * 发票列表
     */
    @PostMapping("list/{page}/{size}")
    public ResponseResult list(@PathVariable("page") int page, @PathVariable("size") int size, @RequestBody PiInvoice piInvoice) { //参数json字符串
        logger.info("发票列表列表查询");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PageHelper.startPage(page, size);//开启分页查询
            QueryWrapper queryWrapper = new QueryWrapper();
            if (null != piInvoice.getCode()) {
                queryWrapper.like("code", "%" + piInvoice.getCode() + "%");//模糊查询编号

            }
            queryWrapper.ne("isDelete", 0);
            queryWrapper.orderByDesc("createDate");
            List<PiInvoice> users = iPiInvoiceService.list(queryWrapper);//列表查询
            PageInfo pageInfo = new PageInfo(users);//pagehelper封装好的分页实体类，将数据放进去
            result.setResult(pageInfo);

            for (PiInvoice pp : users) {
                PiCustomer pic = iPiCustomerService.getById(pp.getCustomerId());
                pp.setCustomername(pic.getName());
                iPiInvoiceService.saveOrUpdate(pp);
            }

        } catch (Exception e) {
            logger.info("发票列表查询失败,{}", e.toString());
            result.setSuccess(false);
            result.setMessage("查询失败:" + e.toString());
        }
        logger.info("发票列表查询结束");
        return result;
    }

    /**
     * 查看发票
     */
    @GetMapping("getck/{id}")
    public ResponseResult getck(@PathVariable("id") Integer id) {
        logger.info("发票查找明细");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PiInvoice mm = iPiInvoiceService.getById(id);
            result.setResult(mm);
            result.setMessage("查找成功");
        } catch (Exception e) {
            logger.info("发票查找明细失败,{}", e.toString());
            result.setSuccess(false);
            result.setMessage("查找失败:" + e.toString());
        }
        logger.info("发票查找明细结束");
        return result;
    }

    /**
     * 更改发票状态
     */
    @PostMapping("zt/{zt}/{updateUser}")
    public ResponseResult zt(@PathVariable("zt") Integer zt, @PathVariable long updateUser, @RequestBody PiInvoice piInvoice) {
        logger.info("更改发票状态");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            piInvoice.setState(zt);
            piInvoice.setUpdateDate(new Date());
            piInvoice.setUpdateUser(updateUser);
            piInvoice.setUpdateUser(updateUser);
            iPiInvoiceService.saveOrUpdate(piInvoice);
            //添加发票记录
            PiInvoiceLog piInvoiceLog = new PiInvoiceLog();
            piInvoiceLog.setInvoiceId(piInvoice.getId());
            piInvoiceLog.setUserId(updateUser);
            piInvoiceLog.setUserName(iTbUserService.getById(updateUser).getFullName());
            piInvoiceLog.setUpdatetime(new Date());
            if (zt == 1) {
                piInvoiceLog.setRemarks("审核通过");
            } else if (zt == 2) {
                piInvoiceLog.setRemarks("审核不通过,原因如下： "+piInvoice.getRemarks());
            } else if (zt == 3) {
                piInvoiceLog.setRemarks("邮寄");
            }
            iPiInvoiceLogService.save(piInvoiceLog);
            result.setMessage("更改成功");
        } catch (Exception e) {
            logger.info("发票更改发票状态失败,{}", e.toString());
            result.setSuccess(false);
            result.setMessage("更改发票状态失败:" + e.toString());
        }
        logger.info("更改发票状态结束");
        return result;
    }

    @PostMapping("/updatezt/{id}/{zt}")
    public ResponseResult updatezt(@PathVariable("id") Integer id, @PathVariable int zt, @RequestBody PiCustomer PiCustomer) {
        logger.info("确认收货开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PiInvoice piInvoice = iPiInvoiceService.getById(id);
            piInvoice.setState(zt);
            iPiInvoiceService.saveOrUpdate(piInvoice);

            //添加发票记录
            PiInvoiceLog piInvoiceLog = new PiInvoiceLog();
            piInvoiceLog.setInvoiceId(piInvoice.getId());
            piInvoiceLog.setUserId(PiCustomer.getId());
            piInvoiceLog.setUserName(iTbUserService.getById(PiCustomer.getId()).getFullName());
            piInvoiceLog.setRemarks("确认收货");
            piInvoiceLog.setUpdatetime(new Date());
            iPiInvoiceLogService.save(piInvoiceLog);


            result.setMessage("确认收货成功");
        } catch (Exception e) {
            logger.info("确认收货失败,{}", e.toString());
            result.setSuccess(false);
            result.setMessage("确认收货失败:" + e.toString());
        }
        logger.info("确认收货结束");
        return result;
    }

    @PostMapping("/ycorder/{id}")
    public ResponseResult ycorder(@PathVariable("id") Integer id, @RequestBody PiCustomer piCustomer) {
        logger.info("隐藏发票开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PiInvoice piInvoice = iPiInvoiceService.getById(id);
            piInvoice.setIsDelete(3);
            iPiInvoiceService.saveOrUpdate(piInvoice);
            result.setMessage("隐藏发票成功");
        } catch (Exception e) {
            logger.info("隐藏发票失败,{}", e.toString());
            result.setSuccess(false);
            result.setMessage("隐藏发票失败:" + e.toString());
        }
        logger.info("隐藏发票结束");
        return result;
    }@PostMapping("/delInvoice/{id}")
    public ResponseResult delInvoice(@PathVariable("id") Integer id, @RequestBody PiCustomer piCustomer) {
        logger.info("删除发票开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PiInvoice piInvoice = iPiInvoiceService.getById(id);
            piInvoice.setIsDelete(0);
            iPiInvoiceService.saveOrUpdate(piInvoice);
            //添加发票记录
            PiInvoiceLog piInvoiceLog = new PiInvoiceLog();
            piInvoiceLog.setInvoiceId(piInvoice.getId());
            piInvoiceLog.setUserId(piCustomer.getId());
            piInvoiceLog.setUserName(iTbUserService.getById(piCustomer.getId()).getFullName());
            piInvoiceLog.setRemarks("删除发票信息");
            piInvoiceLog.setUpdatetime(new Date());
            iPiInvoiceLogService.save(piInvoiceLog);
            result.setMessage("删除发票成功");
        } catch (Exception e) {
            logger.info("删除发票失败,{}", e.toString());
            result.setSuccess(false);
            result.setMessage("删除发票失败:" + e.toString());
        }
        logger.info("删除发票结束");
        return result;
    }
}
